<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加藤惠聊天</title>
    <style>
        /* 样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #fdf2f8;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 600px;
            height: 80vh;
            max-height: 700px;
            background-color: #fff;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(224, 130, 172, 0.15);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background-color: #f9a8d4;
            color: #fff;
            padding: 16px;
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            border-bottom: 1px solid #fecdd3;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #fef7fb;
        }

        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background-color: #f9a8d4;
            border-radius: 3px;
        }

        .message {
            margin-bottom: 16px;
            max-width: 80%;
            padding: 10px 14px;
            border-radius: 18px;
            line-height: 1.5;
            word-wrap: break-word;
        }

        .user-message {
            background-color: #f9a8d4;
            color: #fff;
            margin-left: auto;
            border-bottom-right-radius: 4px;
        }

        .ai-message {
            background-color: #f0f0f0;
            color: #333;
            margin-right: auto;
            border-bottom-left-radius: 4px;
            position: relative;
        }

        .ai-message::before {
            content: '';
            position: absolute;
            left: -8px;
            top: 12px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background-image: url('https://picsum.photos/id/64/100'); /* 加藤惠头像，可替换 */
            background-size: cover;
            border: 2px solid #fff;
        }

        .typing-indicator {
            display: inline-flex;
            gap: 4px;
            padding: 8px 12px;
        }

        .typing-indicator span {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #999;
            animation: typing 1.4s infinite ease-in-out both;
        }

        .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }

        .chat-input {
            display: flex;
            padding: 16px;
            background-color: #fff;
            border-top: 1px solid #fecdd3;
        }

        #user-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #f9a8d4;
            border-radius: 24px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        #user-input:focus {
            border-color: #f472b6;
        }

        #send-btn {
            margin-left: 12px;
            padding: 12px 20px;
            background-color: #f9a8d4;
            color: #fff;
            border: none;
            border-radius: 24px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        #send-btn:hover {
            background-color: #f472b6;
        }

        #send-btn:disabled {
            background-color: #fecdd3;
            cursor: not-allowed;
        }

        .welcome-message {
            text-align: center;
            margin: 20px 0;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-header">加藤惠的聊天窗口</div>
    <div class="chat-messages" id="chat-messages">
        <div class="welcome-message">你好呀～ 我是加藤惠，有什么想跟我说的吗？😊</div>
    </div>
    <div class="chat-input">
        <input type="text" id="user-input" placeholder="输入想对惠说的话..." autocomplete="off">
        <button id="send-btn">发送</button>
    </div>
</div>

<script>
        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');

        // 后端接口地址（确保和后端一致）
        const API_URL = '/chat/ai';

        // 发送消息
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            // 添加用户消息到界面
            addMessageToUI('user', message);
            userInput.value = '';
            disableInput(true);

            // 添加AI正在输入状态
            const typingElement = addTypingIndicator();

            try {
                // 调用后端流式接口
                const response = await fetch(`${API_URL}?userInput=${encodeURIComponent(message)}`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'text/event-stream'
                    }
                });

                if (!response.ok) throw new Error('请求失败');

                // 处理流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let aiMessage = '';

                // 移除正在输入状态，添加AI消息容器
                typingElement.remove();
                const aiMessageElement = addMessageToUI('ai', '');

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    // 解码并拼接消息
                    const chunk = decoder.decode(value, { stream: true });
                    aiMessage += chunk;

                    // 第一步：过滤所有"data:"前缀
                    let filteredMessage = aiMessage.replace(/data:/g, '');
                    // 第二步：过滤连续空格，保留单空格（或直接去除所有空格）
                    filteredMessage = filteredMessage.replace(/\s+/g, ''); // 去除所有空格
                    // 若需保留单空格，可改为：filteredMessage = filteredMessage.replace(/\s+/g, ' ');

                    // 更新AI消息显示
                    aiMessageElement.textContent = filteredMessage;
                    scrollToBottom();
                }
            } catch (error) {
                typingElement.remove();
                addMessageToUI('ai', '抱歉呀，发生了错误呢～ 请稍后再试～');
                console.error('错误:', error);
            } finally {
                disableInput(false);
            }
        }

        // 添加消息到界面
        function addMessageToUI(sender, content) {
            const messageElement = document.createElement('div');
            messageElement.className = `message ${sender}-message`;
            messageElement.textContent = content;
            chatMessages.appendChild(messageElement);
            scrollToBottom();
            return messageElement;
        }

        // 添加正在输入指示器
        function addTypingIndicator() {
            const typingElement = document.createElement('div');
            typingElement.className = 'message ai-message';
            typingElement.innerHTML = `
                <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            `;
            chatMessages.appendChild(typingElement);
            scrollToBottom();
            return typingElement;
        }

        // 滚动到底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 禁用/启用输入框和按钮
        function disableInput(disabled) {
            userInput.disabled = disabled;
            sendBtn.disabled = disabled;
        }

        // 事件监听
        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') sendMessage();
        });

        // 页面加载完成后聚焦输入框
        window.addEventListener('load', () => {
            userInput.focus();
        });
    </script>
</body>
</html>